package businessServlets;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.tools.ant.taskdefs.Sleep;
import org.omg.CORBA.portable.Streamable;

import sessionMenegment.SessionMgr;
import validate.Validate;


import com.google.appengine.api.datastore.Email;
import com.google.appengine.api.datastore.PhoneNumber;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.sun.xml.internal.ws.developer.MemberSubmissionAddressing.Validation;
import com.tecnick.htmlutils.htmlentities.HTMLEntities;


import controller.Controller;
import java.util.logging.Logger;

@SuppressWarnings("serial")
public class CreateAccountBusiness extends HttpServlet {
	private static final Logger log = Logger.getLogger(CreateAccountBusiness.class.getName());
	ImagesService imagesService = ImagesServiceFactory.getImagesService(); 
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("sign in get =)");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//resp.setContentType("text/plain");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		System.out.println(isMultipart);
		
		
		if (!isMultipart)
		{
			String brows = req.getParameter("brows");
			boolean ie = false;
			if(brows!=null && brows.equals("ie"))
				ie=true;
			log.warning("Brows="+brows);
			log.warning("IE="+ie);
			System.out.println("HIIIIIIII");
			System.out.println("type: "+req.getContentType());
			System.out.println("encoding: "+req.getCharacterEncoding());
			String userName = req.getParameter("userName");
			req.getSession().setAttribute("userNameBusiness", userName);
			String password = req.getParameter("password");
			String password1 = req.getParameter("password1");
			Email email = new Email(req.getParameter("email"));
			//String businessName = req.getParameter("businessName");
			String businessName = getParameter(req.getParameter("businessName"),ie);
			String bizType = req.getParameter("bizTypeSelect");
			String businessNumber = req.getParameter("businessNumber");
			PhoneNumber phone = new PhoneNumber(req.getParameter("phone"));
			String background = req.getParameter("background");
			String secBackground = req.getParameter("secBackground");
			String borderColor = req.getParameter("borderColor");
			String website = getParameter(req.getParameter("site"),ie);//req.getParameter("site");
			String skypeLogin = req.getParameter("skypeLogin");
			
			//businessName =new String(businessName.getBytes("UTF-8"),"ISO-8859-1");
			System.out.println(userName + " " + password + " " + password1 + " "+ email.getEmail() + " "+ businessName + " "+  businessNumber +" " + phone.getNumber());
			
			ArrayList<String> status = new ArrayList<String>();
			int i=0;
			
			while (req.getParameter("list_"+i)!=null)
			{
				System.out.println("list_"+getParameter(req.getParameter("list_"+i),ie));
				status.add(getParameter(req.getParameter("list_"+i),ie));
				i++;
			}
			
			ArrayList<String> message = new ArrayList<String>();
			i=0;
			
			while (req.getParameter("message_"+i)!=null)
			{
				System.out.println("message_"+getParameter(req.getParameter("message_"+i),ie));
				message.add(getParameter(req.getParameter("message_"+i),ie));
				i++;
			}
			
			Controller.getInstance().newBisAccount(businessName,bizType, businessNumber, null, phone, email,website, userName, password, status, null, message,
					background, secBackground,  borderColor, "");
			
			//System.out.println(req.getParameter("logo"));
			
			
			//resp.getWriter().println(req.getParameter("userName")+", welcome! =)");
			//resp.sendRedirect("/business/addOrder.jsp");
			resp.sendRedirect("allOrders.jsp");
		}
		else
		{
			
			System.out.println("BYEEEEEEEEEEEEEE");
			try { 
				
				HashMap<String, String> formFields = new HashMap<String, String>();
				
				System.out.println("multi");
				ServletFileUpload upload = new ServletFileUpload();       
				//resp.setContentType("text/plain");
				String name;
				String value;
				boolean ie = false;

				FileItemIterator iterator = upload.getItemIterator(req); 
				
				byte[] imageBytes = null;
				while (iterator.hasNext()) {         
					FileItemStream item = iterator.next(); 
					InputStream stream = item.openStream();
				
					//string field
					if (item.isFormField()) {
						
						name = item.getFieldName();
						if(ie)
							value = getParameter(Streams.asString(stream,"UTF-8"),ie);
						else
							value = Streams.asString(stream);
						if(!ie && name.equals("brows") && value.equals("ie"))
							ie=true;
						//System.out.println("form field " + name + " value: "+getParameter(value,ie));
						formFields.put(name, value);
												
					}
					else //image
					{
						
						try
						{
							int len;           
							imageBytes = IOUtils.toByteArray(stream);
							
							if (imageBytes.length==0)
							{
								System.out.println("size 0 -> no image");
								imageBytes = null;
							}
							
							
							//resp.getOutputStream().write(newImage.getImageData(), 0, newImage.getImageData().length);
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println("not image");
						}
						
					}
				} //end while
				
				
				log.warning("IE2="+ie);
				String userName = formFields.get("userName");
				req.getSession().setAttribute("userNameBusiness", userName);
				String password = formFields.get("password");
				String password1 = formFields.get("password1");
				Email email = new Email(formFields.get("email"));
				String businessName = formFields.get("businessName");
				//businessName = getParameter(businessName, ie);
				String bizType = formFields.get("bizTypeSelect");
				String businessNumber = formFields.get("businessNumber");
				PhoneNumber phone = new PhoneNumber(formFields.get("phone"));
				String background = formFields.get("background");
				String secBackground = formFields.get("secBackground");
				String borderColor = formFields.get("borderColor");
				String website = formFields.get("site");
				String skypeLogin = req.getParameter("skypeLogin");
				//website = getParameter(website, ie);
				System.out.println(userName + " " + password + " " + password1 + " "+ email.getEmail() + " "+ businessName + " "+  businessNumber +" " + phone.getNumber());
				
				ArrayList<String> status = new ArrayList<String>();
				int i=0;
				
				while (formFields.get("list_"+i)!=null)
				{
					System.out.println("list_"+getParameter(formFields.get("list_"+i),ie));
					status.add(new String(formFields.get("list_"+i).substring(5).replaceAll("_", " ")));
					i++;
				}
				
				ArrayList<String> message = new ArrayList<String>();
				i=0;
				
				while (formFields.get("message_"+i)!=null)
				{
					System.out.println("message_"+getParameter(formFields.get("message_"+i),ie));
					message.add(new String(formFields.get("message_"+i).substring(5).replaceAll("_", " ")));
					i++;
				}
				
				String validString = Validate.checkBizValid(businessName, businessNumber, imageBytes, phone, email, userName, password,password1, status, null, message);
				
				if (validString.equals(""))
				{
					PhoneNumber newPhone = new PhoneNumber(phone.getNumber().replaceAll("-", ""));
					int result = Controller.getInstance().newBisAccount(businessName,bizType, businessNumber, imageBytes, newPhone, email,website, userName, password, status, null, message,
							background, secBackground,  borderColor,"");
					
					switch (result)
					{
					case 0:
						req.getSession().removeAttribute("validErrorBiz");
						Thread.sleep(300);
						SessionMgr.getInst().registerUser(req.getSession(), userName,"biz");
						resp.sendRedirect("allOrders.jsp");
						break;
					case 1:
						req.getSession().setAttribute("validErrorBiz","username already exists");
						resp.sendRedirect("home.jsp#joinbiz");
						break;
					case 2:
						req.getSession().setAttribute("validErrorBiz","business name already exists");
						resp.sendRedirect("home.jsp#joinbiz");
						break;						
					}
						
						
				}
				else
				{
					req.getSession().setAttribute("validErrorBiz",validString);
					resp.sendRedirect("home.jsp#joinbiz");
				}
					
				
				//saveImage(imageBytes,userName);
				
				
				

			} catch (Exception ex) {
				throw new ServletException(ex);     
			}
		} // end if
		
		
		//resp.sendRedirect("allOrders.jsp");
	} // end function
		

	private String getParameter(String param,boolean ie){
		log.warning("getParameter "+param);
		if(ie){
			log.warning("if(ie) "+HTMLEntities.htmlentities(param));
			return HTMLEntities.htmlentities(param);
		}
		return param;
	}
	
}
